package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * 会员相关操作
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    /**
     * 增加新的功能：当连续三次验证码输入错误时，将该账户进行冻结，24小时后才可登陆！
     * 思路：
     * 请求来时，与redis中的密码进行比对，如果错误，创建一个session对象，键为手机号，值为错误次数
     * 错误增加，次数增加
     * 当次数大约>3时，直接返回请于24h后登陆
     *
     * @param response
     * @param map
     * @return
     */
    //手机号快速登录
    @RequestMapping("/login")
    public Result login(HttpServletRequest request, HttpServletResponse response, @RequestBody Map map) {
        //获取用户手机号
        String telephone = (String) map.get("telephone");
        //获取验证码
        String validateCode = (String) map.get("validateCode");
        //从redis中取出登录的验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //验证码不匹配
        if (codeInRedis == null || !codeInRedis.equals(validateCode)) {
            Integer errorCount = Integer.parseInt(jedisPool.getResource().get(telephone + "errorCount"));
            if (errorCount == null) {
                jedisPool.getResource().set(telephone + "errorCount", Integer.toString(1));
            } else {
                jedisPool.getResource().set(telephone + "errorCount", Integer.toString(errorCount++));
            }

            if (errorCount > 3) {
                jedisPool.getResource().setex(telephone + "errorCount", 60 * 60 * 24, Integer.toString(4));
                return new Result(false, "您的账户已被冻结，请于24h后完成登录操作！");
            } else {
                //验证码输入错误
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
           /* //获取session对象
            HttpSession session = request.getSession();
            //先查询是否存在该session对象
            Integer errorCount = (Integer) session.getAttribute(telephone);

            if (errorCount==null){
                session.setAttribute(telephone,1);
            }else{
                session.setAttribute(telephone,errorCount++);
            }

            if ((Integer)session.getAttribute(telephone)>3){
                return new Result(false,"您的账户已被冻结，请于24h后完成登录操作！");
            }else{
                //验证码输入错误
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
                ？？如何保证限制的用户在24h后自动清除呢？？
            }*/
        } else {
            //验证码输入正确
            //判断其是否是会员，不是会员要注册为会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //当前用户非会员，自动完成注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //登陆成功=》写入rookie
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");//路径
            //响应出去
            response.addCookie(cookie);
            //保存信息到redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60 * 30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }

    }

}
